package DD3;

import java.util.concurrent.locks.ReentrantLock;
//import this package to use lock
class Window implements Runnable{

    private int money = 110;

    private  static ReentrantLock LK = new ReentrantLock();

    @Override
    public void run() {
        while(true){
            try{
            	LK.lock();	
                if(money >=20){

                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    money-=20;
                    System.out.println(Thread.currentThread().getName() + " take money,money left " + money);
                }else{
                    break;
                }
            }finally {
            	LK.unlock(); // unlock the thread
            }

        }
    }
}

public class LockTest6 {
    public static void main(String[] args) {
        Window w = new Window();

        Thread t1 = new Thread(w);
        Thread t2 = new Thread(w);
        Thread t3 = new Thread(w);

		t1.setName("Person1");
		t2.setName("Person2");
		t3.setName("Person3");

        t1.start();
        t2.start();
        t3.start();
    }
}
